package com.xl.xlserver.mode.login;

import com.alibaba.fastjson.JSONObject;
import com.xl.xlserver.GameUtilEntity.ScokectMessger;
import com.xl.xlserver.constant.LoginModeCode;
import com.xl.xlserver.entity.GameDistrict;
import com.xl.xlserver.entity.GamePlay;
import com.xl.xlserver.entity.GameUser;
import com.xl.xlserver.gameServer.LobbyManager;
import com.xl.xlserver.service.ServiceConpent;
import com.xl.xlserver.utils.AjaxResult;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LoginMode {

    Logger logger = LoggerFactory.getLogger(LoginMode.class);



    public  void codeLogin(ScokectMessger manger, ChannelHandlerContext ctx){
       Map<String,Object> result = new HashMap<>();
        //获取业务码
        int code = manger.getModeCode();
        if (code == LoginModeCode.INIT){
            ctx.writeAndFlush("服务端:"+JSONObject.toJSONString(result));
        }
        if (code == LoginModeCode.Login){
            //登录
           String str = UserLogin(manger,ctx);
            System.out.println("返回信息:"+str);
            ByteBuf resp = Unpooled.copiedBuffer(str.getBytes());
            ctx.write(resp);
        }
        if (code == LoginModeCode.ADDUSER){
            //注册
        }
        if (code == LoginModeCode.OFFLINE){
            //退出
        }if (code == LoginModeCode.GETSERVER){
            //获取服务器
            String str  = getXlServer(manger, ctx);
            ByteBuf resp = Unpooled.copiedBuffer(str.getBytes());
            System.out.println("返回服务器信息"+str);
            ctx.write(resp);
        }if (code  == LoginModeCode.GETPlays){
            //获取角色
           String str = getServerPlay(manger,ctx);
            ByteBuf resp = Unpooled.copiedBuffer(str.getBytes());
            System.out.println("返回服务器信息"+str);
            ctx.write(resp);
        }
    }

    /**
     * 登录验证方法
     * @return
     */
    private  String UserLogin(ScokectMessger messger,ChannelHandlerContext ctx){
        //Map<String,Object> result = new HashMap<>();
        AjaxResult result = new AjaxResult();
        String data;
         if (!StringUtils.isEmpty(messger.getData())) {
             Map userData = JSONObject.parseObject(messger.getData(), HashMap.class);
             String username = (String) userData.get("username");
             String password = (String)userData.get("password");
             if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
                result =  AjaxResult.error("账号密码不可以为空");
                 data = JSONObject.toJSONString(result);
                 return  data;
             }
           GameUser user = ServiceConpent.GameUserService.selectByName(username);
             if (ObjectUtils.isEmpty(user)){
                 result =  AjaxResult.error("用户不存在");
                 data = JSONObject.toJSONString(result);
                 return  data;
             }else if (!user.getPassword().equals(password)){
                 result =  AjaxResult.error("密码错误");
                 data = JSONObject.toJSONString(result);
                 return  data;
             }
             Map<String,Object> userput= new HashMap<>();
             userput.put("ctxId",ctx.channel().id().toString());
             userput.put("user",user);
             LobbyManager.getInstance().addUser(ctx.channel().id().toString(),userput);
             logger.info("["+username+"]登录成功加入用户"+ctx.name());
             result.put("code",200);
             result.put("msg","登录成功");
             data = JSONObject.toJSONString(result);
             return  data;
         }
        result.put("code",500);
        result.put("msg","发生错误");
        result.put("data","null");
        data = JSONObject.toJSONString(result);
        return  data;
     }

     public String getXlServer(ScokectMessger messger,ChannelHandlerContext ctx){
     List<GameDistrict> list =  ServiceConpent.GameDistrictService.list();
     Map<String,Object> result = new HashMap<>();
         result.put("code",200);
         result.put("data",JSONObject.toJSONString(list));
         result.put("msg","获取成功");
       return JSONObject.toJSONString(result);
     }

    public String getServerPlay(ScokectMessger messger,ChannelHandlerContext ctx){
        GamePlay gamePlay = new GamePlay();
        List<GamePlay> plays  = new ArrayList<>();
        Map map = (Map) LobbyManager.getInstance().getUser(ctx.name());
       String userId =  ((GameUser)map.get("user")).getUserId();
        if (StringUtils.isEmpty(messger.getData())&& !StringUtils.isEmpty(userId)){
            gamePlay.setUserId(userId);gamePlay.setDistId(1);
         plays =  ServiceConpent.GamePlayService.getPlayList(gamePlay);

        }
        Map<String,Object> result = new HashMap<>();
        result.put("code",200);
        result.put("data",JSONObject.toJSONString(plays));
        result.put("msg","获取成功");
        return JSONObject.toJSONString(result);
    }
    /**
     * 新增用户方法
     */
    public Object addUser(){
return null;
    }
}
